package com.graphics;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Test_2 extends JFrame  {
    private MyPanel_2 mp=null;
    public static void main(String[] args) {
        Test_2 test_2 = new Test_2();

    }
    public Test_2(){
        mp=new MyPanel_2();
        this.add(mp);
        this.addKeyListener(mp);
        this.setSize(1080,680);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
}

class MyPanel_2 extends JPanel implements KeyListener{
    private Dog dog=null;
    public MyPanel_2(){
        dog=new Dog(100,100);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.fillRect(0,0,1080,680);
        g.setColor(Color.green);
        g.fillOval(dog.getX(),dog.getY(),80,80);
    }


    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode()==KeyEvent.VK_DOWN){
            dog.movedown();
        } else if (e.getKeyCode()==KeyEvent.VK_UP) {
            dog.moveup();
        }
        else if(e.getKeyCode()==KeyEvent.VK_RIGHT){
            dog.moveright();
        }
        else if(e.getKeyCode()==KeyEvent.VK_LEFT){
            dog.moveleft();
        }
        repaint();
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }
}

class Dog{
    private int x;
    private int y;
    private int speed=10;//速度

    public void moveup(){
        y-=speed;
    }
    public void moveright(){
        x+=speed;
    }
    public void movedown(){
        y+=speed;
    }
    public void moveleft(){
        x-=speed;
    }
    public Dog(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getSpeed() {
        return speed;
    }

    public void setSpeed(int speed) {
        this.speed = speed;
    }
}